import axios from 'axios'
import errorCode from '@/const/errorCode'
import { Toast } from 'vant'
const CURRENT_PROJECT_NAME = 'cockpit' // 当前项目名称
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

service.interceptors.request.use(
  async(config) => {
    const { token } = await window.nativeHandler()
    config.headers['Authorization'] = token
    // 本地开发时匹配本地代理的接口基础地址
    if (process.env.NODE_ENV === 'development') {
      config.baseURL = `/${config.projectName || CURRENT_PROJECT_NAME}`
      return config
    }
    // 非本地开发时，通过底座方法获取当前对应应用、对应环境的接口基础地址
    const { data } = await window.nativeHandler('getServerUrl', '')
    config.baseURL = data + (config.projectName || CURRENT_PROJECT_NAME)
    return config
  },
  (error) => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res) {
      const status = Number(response.status) || 200
      const message =
                res.msg || errorCode[status] || errorCode['default']
      if (status === 401 || res.code === 401 || res.code === '401') {
        // TODO:后期考虑是否可刷新token refreshToken
        Toast({
          message: errorCode['401'],
          duration: 2000,
          forbidClick: true
        })
        return
      }
      if (status !== 200 || res.success === 0) {
        Toast({
          message: message || '未知原因，请联系管理员',
          duration: 2000,
          forbidClick: true
        })
        return Promise.reject(new Error(message))
      }
      return Promise.resolve(res)
    } else {
      return Promise.reject(new Error('系统异常'))
    }
  },
  (error) => {
    console.log('err' + error) // for debug
    const res = error.response.data
    const status = Number(error.response.status) || 200
    const message = res.msg || errorCode[status] || errorCode['default']
    if (status === 401 || res.code === 401 || res.code === '401') {
      Toast({
        message: errorCode['401'] || '未知原因，请联系管理员',
        duration: 2000,
        forbidClick: true
      })
      return Promise.reject(message)
    }
    return Promise.reject(error)
  }
)

export default service
